Skip to content

구글 OAuth2 로그인 기능#156

Open
Goldbar97 wants to merge 3 commits intoESJung95:developfrom
Goldbar97:feat/OAuth2Google
Open

구글 OAuth2 로그인 기능#156
Goldbar97 wants to merge 3 commits intoESJung95:developfrom
Goldbar97:feat/OAuth2Google

Conversation

@Goldbar97
Copy link
Copy Markdown
Collaborator

변경사항

AS-IS

  • OAuth2 를 이용한 구글 로그인 기능 없음

TO-BE

  • OAuth2 기능 추가로 구글 계정으로 서비스 이용 가능
    • 구글 계정으로 로그인 시 GoogleOAuth2Service 에서 처리하며 CandidateEntity 는 다음과 같은 특별한 key 를 가짐
    String key = oAuth2Response.getProvider() + "-" + oAuth2Response.getProviderId();
    • SecurityConfig 에 다음과 같은 설정을 추가함
    //OAuth2 설정
    .oauth2Login(oauth2customizer -> oauth2customizer.userInfoEndpoint(
            userInfoEndpointConfig -> userInfoEndpointConfig.userService(googleOAuth2Service))
        .successHandler(googleOAuth2AuthenticationSuccessHandler))
    • 로그인 성공 시 다음과 같은 handler 를 사용하고 첫 로그인 시 임의의 값으로 설정된 Entity 로 저장함. 테스트 용으로 로그인 성공 시 /common/job-positngs 로 리디렉션 하고 JWT 토큰 값을 전달함.
      @Transactional
      public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response,
          Authentication authentication) throws IOException, ServletException {
    
        OAuth2User oAuth2User = (OAuth2User) authentication.getPrincipal();
    
        CandidateEntity candidateEntity = candidateRepository.findByCandidateKey(oAuth2User.getName())
            .orElseGet(() -> {
              CandidateEntity newCandidate = CandidateEntity.builder()
                  .candidateKey(oAuth2User.getName())
                  .name(oAuth2User.getAttribute("name"))
                  .email(oAuth2User.getAttribute("email"))
                  .password(keyGenerator.generateKey())
                  .phoneNumber("undefinedNumber")
                  .role(UserRole.ROLE_CANDIDATE)
                  .build();
    
              candidateRepository.save(newCandidate);
    
              return newCandidate;
            });
    
        String token = jwtTokenProvider.generateToken(candidateEntity.getEmail(),
            candidateEntity.getRole());
    
        response.setHeader("Authorization", "Bearer " + token);
        response.setContentType("application/json");
        response.sendRedirect("/common/job-postings");
      }

@Goldbar97 Goldbar97 self-assigned this Aug 10, 2024
Copy link
Copy Markdown
Owner

@ESJung95 ESJung95 left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Google OAuth는 처음봐서 신기하군요ㅋㅋㅋ 시간될 때 설명도 부탁드릴게요!

runtimeOnly 'io.jsonwebtoken:jjwt-jackson:0.11.5'

// OAuth2
implementation 'org.springframework.boot:spring-boot-starter-oauth2-client'
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

이거 추가안해줘도 되는 줄 알았는데.. 아니군요ㅜ.ㅜ

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ESJung95 님은 라이브러리 추가 없이 작동됐나요?

.name(oAuth2User.getAttribute("name"))
.email(oAuth2User.getAttribute("email"))
.password(keyGenerator.generateKey())
.phoneNumber("undefinedNumber")
Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

일단 이렇게 생성해서 DB 저장시킨거죠..? 따로 핸드폰번호까지 리다이렉트해서 받아오는 로직은 아직 없는거 맞나요?ㅜㅜ

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

네 일단 저렇게 회원 엔티티 만들어지게 했습니다

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants